package com.oa.dao.impl;

import com.oa.common.base.Page;
import com.oa.common.base.Pageable;
import com.oa.common.eums.EntityStatus;
import com.oa.common.interfaces.PreFilter;
import com.oa.dao.AppsTypeDao;
import com.oa.dao.BaseDaoImpl;
import com.oa.dao.PreFilters;
import com.oa.entities.flows.AppType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Repository
public class AppsTypeDaoImpl extends BaseDaoImpl<Long,AppType> implements AppsTypeDao {

    @Override
    protected void loadClassType() {
        setType(AppType.class);
    }

    @Autowired
    private JdbcTemplate template;

    @Override
    public Page<AppType> findPage(Pageable pageable, String key,Integer type) {
        List<PreFilter> filters= new ArrayList<>();
        filters.add(PreFilters.eq(AppType.PROP_STATUS,EntityStatus.ENTITY_EABLE.getCode()));
        if(!StringUtils.isEmpty(key)){
            filters.add(PreFilters.like(AppType.APP_TYPE_TITLE,"%"+key+"%"));
        }
        if (type!=null){
            filters.add(PreFilters.eq(AppType.APP_TYPE_FILETYPE,type));
        }
        pageable.setFilters(filters);
        return findPage(pageable);
    }

    @Override
    public Boolean validate(String title, Long id) {
        List<PreFilter> filters= new ArrayList<>();
        filters.add(PreFilters.eq(AppType.PROP_STATUS,EntityStatus.ENTITY_EABLE.getCode()));
        filters.add(PreFilters.eq(AppType.APP_TYPE_TITLE,title));
        if (id!=null){
            filters.add(PreFilters.noteq(AppType.PROP_ID,id));
        }
        PreFilter[] fs= new PreFilter[filters.size()];
        return findUnqiue(filters.toArray(fs))!=null;
    }

    @Override
    public void createTable(Long id) {
        StringBuilder builder= new StringBuilder();
        builder.append("CREATE TABLE oa_apps_"+id+" (");
        builder.append("id int(11) NOT NULL AUTO_INCREMENT,");
        builder.append("appid bigint(20) NOT NULL,");
        builder.append("tplid bigint(20) NOT NULL,");
        builder.append("tpltype int(11) NOT NULL,");
        builder.append("date bigint(20) DEFAULT NULL,");
        builder.append("PRIMARY KEY (id)");
        builder.append(") ENGINE=MyISAM AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;");
        template.execute(builder.toString());
    }
}
